package com.magnificent.atlantis.server.database.message;

import com.magnificent.atlantis.common.entity.ServerMeeting;
import com.magnificent.atlantis.common.entity.messages.ServerMessage;
import com.magnificent.atlantis.common.entity.messages.ServerReInviteMessage;
import com.magnificent.atlantis.common.entity.messages.ServerUpdateMeetingMessage;
import com.magnificent.atlantis.server.database.AtlantisDataSource;
import com.magnificent.atlantis.server.database.utils.ServerMessageHelper;
import com.magnificent.commons.db.datasource.ObjectEntity;

import java.util.ArrayList;
import java.util.Date;

/**
 * User: Babanin
 * Date: 06.05.2009
 * Time: 12:44:57
 */
public class UpdateMeetingMessageHandler extends MessageHandler {
    public ObjectEntity handleMessage(ServerMessage message) {
        ServerUpdateMeetingMessage updateMeetingMessage = (ServerUpdateMeetingMessage) message;
        ServerMeeting serverMeeting = AtlantisDataSource.getInstance().getMeeting(updateMeetingMessage.getEventId());

        String oldTitle = serverMeeting.getTitle();
        ServerMessageHelper.merge(serverMeeting, updateMeetingMessage);
        serverMeeting.setCanceledByUsers(new ArrayList<Integer>());

        AtlantisDataSource.getInstance().update(serverMeeting);

        if (updateMeetingMessage.isReInvite()) {
            ArrayList<Integer> invitedUsers = serverMeeting.getInvitedUsers();
            for (Integer invitedUser : invitedUsers) {
                if (updateMeetingMessage.getUserFromId() != invitedUser) {
                    AtlantisDataSource.getInstance().persist(generateReInvite(serverMeeting, invitedUser, oldTitle));
                }
            }
        }

        return message;
    }


    private ServerReInviteMessage generateReInvite(ServerMeeting serverMeeting,
                                                   Integer invitedUser, String oldTitle) {
        ServerReInviteMessage inviteMessage = new ServerReInviteMessage();

        inviteMessage.setOldTitle(oldTitle);
        inviteMessage.setSentDate(new Date());
        inviteMessage.setUserToId(invitedUser);
        inviteMessage.setDate(serverMeeting.getDate());
        inviteMessage.setTitle(serverMeeting.getTitle());
        inviteMessage.setEventId((int) serverMeeting.getId());
        inviteMessage.setComment(serverMeeting.getDescription());
        inviteMessage.setInvited(serverMeeting.getInvitedUsers());
        inviteMessage.setUserFromId(serverMeeting.getModeratorId());

        return inviteMessage;
    }
}
